﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ext.Net;

public partial class SYS_POPEDOM_User_Create : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BuildTreeRoot();
            CreatTmpTable();
            if (Request.QueryString["ObjId"] != null && Request.QueryString["ObjId"].ToString() != "Add")
            {
                ViewState["ObjId"] = Request.QueryString["ObjId"].ToString();
                DataTable tmptable = CommonLib.BLL.SYS_USER.GetList("user_id='" + Request.QueryString["ObjId"] + "'").Tables[0];
                SetFormLayout(FormLayout3, tmptable);
                SetFormLayout(FormLayout2, tmptable);
                SetFormLayout(FormLayout4, tmptable);
                SetFormLayout(FormLayout15, tmptable);
                if (tmptable.Rows.Count > 0)
                {
                    string sDecode = tmptable.Rows[0]["USER_PASSWORD"].ToString();
                    exttxtf_USER_PASSWORD.Text = CommonLib.ComMon.StringCommon.StringDecode(sDecode);
                }
                else
                {
                    exttxtf_USER_PASSWORD.Text = "";
                }
                BindGrid(Request.QueryString["ObjId"]);
                if (tmptable.Rows[0]["IS_MANAGER"].ToString() != "")
                {
                    if (tmptable.Rows[0]["IS_MANAGER"].ToString() == "1")
                    {
                        rdoIS_MANAGER1.Checked = true;
                        rdoIS_MANAGER2.Checked = false;
                    }
                    else
                    {
                        rdoIS_MANAGER1.Checked = false;
                        rdoIS_MANAGER2.Checked = true;
                    }
                }
                if (tmptable.Rows[0]["dept_id"].ToString() != "")
                    GetDeptBind(tmptable.Rows[0]["dept_id"].ToString());
                exttxtf_user_id.ReadOnly = true;
                exttxtf_user_id.StyleSpec = "background:#fffbf0;";
            }
            else
            {
                ViewState["ObjId"] = "Add";
                if (Request.QueryString["dept_id"] != null)
                    GetDeptBind(Request.QueryString["dept_id"].ToString());
            }

        }
        
    }

    protected void OnExttrig_OTHER_USER1_Click(object sender,DirectEventArgs e)
    {
        string InitValue = exttrig_OTHER_USER1.Text.ToString();
        IniYXUser(InitValue);
    }

    protected void GetPY(object sender, DirectEventArgs e)
    {
        string Name = exttxtf_USER_NAME.Text.Trim();
        if (!string.IsNullOrEmpty(Name))
        {
            exttxtf_USER_PYM.Text = GetPinyinByName(Name);
        }
        DataTable dt_SYS_USER = CommonLib.BLL.SYS_USER.GetList("USER_PYM IS NULL").Tables[0];
        foreach (DataRow item in dt_SYS_USER.Rows)
        {
            CommonLib.Model.SYS_USER model = CommonLib.BLL.SYS_USER.GetModel(Convert.ToString(item["USER_ID"]));
            model.USER_PYM = GetPinyinByName(model.USER_NAME);
            CommonLib.BLL.SYS_USER.Update(model);
        }
    }

    private void IniYXUser(string InitValue)
    {
        String _LowConnect = "";
        String _HighConnect = "";

        _LowConnect = CommonLib.ComMon.BSconfig.GetConfig("YX_LowConn");
        _HighConnect = CommonLib.ComMon.BSconfig.GetConfig("YX_HighConn");

        string strTemp = "";
        string g_yxuser_id = "";
        string strDll = "LookPayDll.dll";
        string entry_parameter = "ShowLookPayWindow";
        int exec_type = 1;
        string r_only = "0";
        strTemp = "InitValue='" + InitValue + "';CallYXDll('" + g_yxuser_id + "','" + strDll + "','" + entry_parameter + "'," + exec_type + ",'" + r_only + "','','" + _HighConnect + "','','',0,'','')";
    }

    private void GetDeptBind(string deptId) //绑定部门ID及下拉框
    {
        DataTable dtt = CommonLib.BLL.SYS_DEPT.GetList("del_flag =0 and  dept_id='" + deptId.Trim() + "'").Tables[0];
        if (dtt.Rows.Count > 0)
        {
            extcobo_DeptName.Value = dtt.Rows[0]["DEPT_NAME"].ToString();
            extHid_coboDeptId.Text = deptId.Trim();
        }
    }
    private void CreatTmpTable()
    {
        DataTable tmptable = new DataTable();
        tmptable.TableName = "tmptable";
        tmptable.Columns.Add("USER_ID", Type.GetType("System.String"));
        tmptable.Columns.Add("MASTER_ID", Type.GetType("System.String"));
        tmptable.Columns.Add("ROLE_NAME", Type.GetType("System.String"));
        tmptable.Columns.Add("DEPT_NAME", Type.GetType("System.String"));
        tmptable.Columns.Add("DEPT_ID", Type.GetType("System.String"));
        tmptable.Columns.Add("CREATOR", Type.GetType("System.String"));

        Session["tmptable"] = tmptable;
    }

    [DirectMethod]
    public void refrashDataEvent(string NodeIds)
    {

        DataTable tmptable = Session["tmptable"] as DataTable;
        string[] menuno = NodeIds.Split(';');
        for (int i = 0; i < menuno.Length; i++)
        {
            DataRow dr = tmptable.NewRow();
            dr["USER_ID"] = ViewState["ObjId"].ToString();
            dr["MASTER_ID"] = menuno[i];
            DataTable dt = CommonLib.BLL.SYS_DEPT_ROLES.GetList(" MASTER_ID=" + int.Parse(menuno[i]) + "").Tables[0];
            dr["ROLE_NAME"] = dt.Rows[0]["ROLE_NAME"].ToString();
            dr["DEPT_NAME"] = dt.Rows[0]["DEPT_NAME"].ToString();
            dr["DEPT_ID"] = dt.Rows[0]["DEPT_ID"].ToString();
            dr["CREATOR"] = dt.Rows[0]["CREATOR"].ToString();
            tmptable.Rows.Add(dr);
        }
        Session["tmptable"] = tmptable;
        Store1.DataSource = tmptable;
        Store1.DataBind();
    }

    //加载列表
    private void BindGrid(string userId)
    {
        DataTable GridData = CommonLib.BLL.SYS_OPERATOR_ROLE.GetList(" user_id='" + userId + "'").Tables[0];
        this.Store1.DataSource = GridData;
        this.Store1.DataBind();
        Session["tmptable"] = GridData;
    }
    
    [DirectMethod]
    public void DelFunc(string sJson)
    {
        DataTable dt = JSON.Deserialize<DataTable>(sJson);
        if (dt.Rows.Count == 0)
        {
            X.Msg.Alert("系统提示", "请先选择要删除的记录！").Show();
            return;
        }
        DataTable tmptable = Session["tmptable"] as DataTable;
        foreach (DataRow row in dt.Select())
        {
            if (row["dept_id"].ToString().IndexOf(BS_LoginDeptId.Trim()) == -1)
            {
                if (row["creator"].ToString() != BS_LoginUserID)
                {
                    X.Msg.Alert("系统提示", "无法删除其他部门的权限！").Show();
                    return;
                }
            }
            DataRow[] tR = tmptable.Select("MASTER_ID='" + row["MASTER_ID"].ToString() + "'");
            tmptable.Rows.Remove(tR[0]);
        }
        tmptable.AcceptChanges();
        Session["tmptable"] = tmptable;
        this.Store1.DataSource = tmptable;
        this.Store1.DataBind();
    }

    #region  以下是弹出窗体代码

    //构建部门树根节点
    private void BuildTreeRoot()
    {
        DataTable tmpDt = CommonLib.BLL.SYS_DEPT.GetListSub(" dept_id='00' and  del_flag =0 ", "dept_id").Tables[0];
        if (tmpDt.Rows.Count == 1)
        {
            Ext.Net.AsyncTreeNode root = new Ext.Net.AsyncTreeNode();
            root.Text = tmpDt.Rows[0]["dept_name"].ToString();
            root.NodeID = tmpDt.Rows[0]["dept_id"].ToString();
            root.Expanded = true;
            root.IconCls = "no-icon";
            if (tmpDt.Rows[0]["leaf"].ToString() == "0")
                root.Leaf = true;
            root.Draggable = true;
            this.TreePanel1.Root.Add(root);
        }
    }

    [DirectMethod]
    public string NodeLoadWin(string nodeID)
    {
        Ext.Net.TreeNodeCollection nodes = new Ext.Net.TreeNodeCollection();
        if (!string.IsNullOrEmpty(nodeID))
        {
            DataTable TreeData = CommonLib.BLL.SYS_DEPT.GetListSub(" del_flag =0 and ltrim(rtrim(dept_id)) like '" + nodeID.Trim() + "__' ", "dept_id").Tables[0];
            for (int i = 0; i < TreeData.Rows.Count; i++)
            {
                AsyncTreeNode asyncNode = new AsyncTreeNode();
                asyncNode.Text = TreeData.Rows[i]["dept_name"].ToString();
                asyncNode.NodeID = TreeData.Rows[i]["dept_id"].ToString();
                asyncNode.IconCls = "no-icon";
                if (TreeData.Rows[i]["leaf"].ToString() == "0")
                    asyncNode.Leaf = true;
                nodes.Add(asyncNode);
            }
            string where = " creator IN (SELECT su.[USER_ID] FROM SYS_USER su WHERE Charindex(RTRIM('" + BS_LoginDeptId + "'),su.DEPT_ID,0) > 0 ) ";
            DataTable TmpTable = CommonLib.BLL.SYS_DEPT_ROLES.GetList(" ltrim(rtrim(dept_id))='" + nodeID.Trim() + "' and " + where).Tables[0];
            DataTable dt = Session["tmptable"] as DataTable;
            for (int m = 0; m < dt.Rows.Count; m++)
            {
                DataRow[] tR = TmpTable.Select("MASTER_ID='" + dt.Rows[m]["MASTER_ID"].ToString() + "'");
                if (tR.Length > 0)
                    TmpTable.Rows.Remove(tR[0]);
            }
            TmpTable.AcceptChanges();
            for (int j = 0; j < TmpTable.Rows.Count; j++)
            {
                Ext.Net.TreeNode treeNode = new Ext.Net.TreeNode();
                treeNode.Text = TmpTable.Rows[j]["ROLE_NAME"].ToString();
                treeNode.NodeID = TmpTable.Rows[j]["MASTER_ID"].ToString();
                treeNode.Leaf = true;
                treeNode.IconCls = "no-icon";
                treeNode.Checked = ThreeStateBool.False;
                nodes.Add(treeNode);
            }
        }
        return nodes.ToJson();
    }

    [DirectMethod]
    public string RefreshMenu()
    {
        Ext.Net.TreeNodeCollection nodes = BuildTree(null);
        return nodes.ToJson();
    }

    private Ext.Net.TreeNodeCollection BuildTree(Ext.Net.TreeNodeCollection nodes)
    {
        string where = " creator IN (SELECT su.[USER_ID] FROM SYS_USER su WHERE Charindex(RTRIM('" + BS_LoginDeptId + "'),su.DEPT_ID,0) > 0 ) ";

        if (nodes == null)
        {
            nodes = new Ext.Net.TreeNodeCollection();
        }
        DataTable tmpDt = CommonLib.BLL.SYS_DEPT.GetListSub(" dept_id='00' and  del_flag =0 ", "dept_id").Tables[0];
        if (tmpDt.Rows.Count == 1)
        {
            Ext.Net.TreeNode root = new Ext.Net.TreeNode();
            root.Text = tmpDt.Rows[0]["dept_name"].ToString();
            root.NodeID = tmpDt.Rows[0]["dept_id"].ToString();
            root.Expanded = true;
            root.IconCls = "no-icon";
            if (tmpDt.Rows[0]["leaf"].ToString() == "0")
                root.Leaf = true;
            root.Draggable = true;
            nodes.Add(root);
            DataTable TreeData = CommonLib.BLL.SYS_DEPT.GetListSub(" del_flag =0 and ltrim(rtrim(dept_id)) like '" + tmpDt.Rows[0]["dept_id"].ToString().Trim() + "__' ", "dept_id").Tables[0];
            DataTable tmpT = null;
            foreach (DataRow dr in TreeData.Rows)
            {
                if (dr["leaf"].ToString() == "0")
                {

                    tmpT = CommonLib.BLL.SYS_DEPT_ROLES.GetList(" ltrim(rtrim(dept_id))='" + dr["dept_id"].ToString().Trim() + "' and " + where).Tables[0];
                    if (tmpT.Rows.Count > 0)
                    {
                        dr.BeginEdit();
                        dr["leaf"] = 1;
                        dr.EndEdit();
                        TreeData.AcceptChanges();
                    }
                }
            }
            for (int i = 0; i < TreeData.Rows.Count; i++)
            {
                AsyncTreeNode asyncNode = new AsyncTreeNode();
                asyncNode.Text = TreeData.Rows[i]["dept_name"].ToString();
                asyncNode.NodeID = TreeData.Rows[i]["dept_id"].ToString();
                asyncNode.IconCls = "no-icon";
                if (TreeData.Rows[i]["leaf"].ToString() == "0")
                    asyncNode.Leaf = true;
                root.Nodes.Add(asyncNode);
            }

            DataTable TmpTable = CommonLib.BLL.SYS_DEPT_ROLES.GetList(" ltrim(rtrim(dept_id))='" + tmpDt.Rows[0]["dept_id"].ToString().Trim() + "' and " + where).Tables[0];
            DataTable dt = Session["tmptable"] as DataTable;
            for (int m = 0; m < dt.Rows.Count; m++)
            {
                DataRow[] tR = TmpTable.Select("MASTER_ID='" + dt.Rows[m]["MASTER_ID"].ToString() + "'");
                if (tR.Length > 0)
                    TmpTable.Rows.Remove(tR[0]);
            }
            TmpTable.AcceptChanges();
            for (int j = 0; j < TmpTable.Rows.Count; j++)
            {
                Ext.Net.TreeNode treeNode = new Ext.Net.TreeNode();
                treeNode.Text = TmpTable.Rows[j]["ROLE_NAME"].ToString();
                treeNode.NodeID = TmpTable.Rows[j]["MASTER_ID"].ToString();
                treeNode.Leaf = true;
                treeNode.IconCls = "no-icon";
                treeNode.Checked = ThreeStateBool.False;
                root.Nodes.Add(treeNode);
            }
        }
        return nodes;
    }
    #endregion

    #region 保存操作
    protected void extBtn_SaveClick(object sender,DirectEventArgs e)
    {
        if (exttxtf_user_id.Text.Trim() == "")
        {
            X.Msg.Alert("系统提示", "操作员编号不能为空！").Show();
            return;
        }
        else
        {
            CommonLib.Model.SYS_USER Model_SysUser = CommonLib.BLL.SYS_USER.GetModel(exttxtf_user_id.Text.Trim());
            if (Model_SysUser != null)
            {
                if (ViewState["ObjId"].ToString() == "Add")
                {
                    X.Msg.Alert("系统提示", "该操作员编号已经有了！").Show();
                    exttxtf_user_id.SetValue("");
                    return;
                }
            }
        }
        if (exttxtf_USER_NAME.Text.Trim() == "")
        {
            X.Msg.Alert("系统提示", "操作员名称不能为空！").Show();
            return;
        }
        if (exttxtf_USER_PASSWORD.Text.Trim() == "")
        {
            X.Msg.Alert("系统提示", "登陆密码不能为空！").Show();
            return;
        }
        if (SaveData())
            X.Msg.Alert("系统提示", "保存成功！").Show();
        else
            X.Msg.Alert("系统提示", "保存失败！").Show();
    }

    private bool SaveData()//保存数据
    {
        bool tmp = true;
        //操作员信息
        CommonLib.Model.SYS_USER Model_SysUser_Original = null;


        CommonLib.Model.SYS_USER Model_SysUser = null;
        if (ViewState["ObjId"].ToString() != "Add")
        {
            Model_SysUser = CommonLib.BLL.SYS_USER.GetModel(ViewState["ObjId"].ToString());
             if (Model_SysUser.DEPT_ID.IndexOf(BS_LoginDeptId.Trim()) == -1)
            {
                Model_SysUser_Original = new CommonLib.Model.SYS_USER();
                Model_SysUser_Original.USER_ID = Model_SysUser.USER_ID;
                Model_SysUser_Original.USER_NAME = Model_SysUser.USER_NAME;
                Model_SysUser_Original.USER_PASSWORD = Model_SysUser.USER_PASSWORD;
                Model_SysUser_Original.USER_TYPE = Model_SysUser.USER_TYPE;
                Model_SysUser_Original.user_duty = Model_SysUser.user_duty;
                Model_SysUser_Original.SUB_SYSTEM = Model_SysUser.SUB_SYSTEM;
                Model_SysUser_Original.REMARK = Model_SysUser.REMARK;
                Model_SysUser_Original.OTHER_USER1 = Model_SysUser.OTHER_USER1;
                Model_SysUser_Original.OTHER_USER2 = Model_SysUser.OTHER_USER2;
                Model_SysUser_Original.OTHER_USER3 = Model_SysUser.OTHER_USER3;
                Model_SysUser_Original.OTHER_PWD1 = Model_SysUser.OTHER_PWD1;
                Model_SysUser_Original.OTHER_PWD2 = Model_SysUser.OTHER_PWD2;
                Model_SysUser_Original.OTHER_PWD3 = Model_SysUser.OTHER_PWD3;
                Model_SysUser_Original.OFFICE_PHONE = Model_SysUser.OFFICE_PHONE;
                Model_SysUser_Original.manage_level = Model_SysUser.manage_level;
                Model_SysUser_Original.it_level = Model_SysUser.it_level;
                Model_SysUser_Original.IS_MANAGER = Model_SysUser.IS_MANAGER;
                Model_SysUser_Original.INNER_PHONE = Model_SysUser.INNER_PHONE;
                Model_SysUser_Original.HOME_PHONE = Model_SysUser.HOME_PHONE;
                Model_SysUser_Original.E_MAIL = Model_SysUser.E_MAIL;
                Model_SysUser_Original.DISPLAY_ORDER = Model_SysUser.DISPLAY_ORDER;
                Model_SysUser_Original.DERATE_LIMIT = Model_SysUser.DERATE_LIMIT;
                Model_SysUser_Original.DEPT_ID = Model_SysUser.DEPT_ID;
                Model_SysUser_Original.DEL_FLAG = Model_SysUser.DEL_FLAG;
                Model_SysUser_Original.CREATE_OPERATOR_ID = Model_SysUser.CREATE_OPERATOR_ID;
                Model_SysUser_Original.CONTACT_PHONE = Model_SysUser.CONTACT_PHONE;
                Model_SysUser_Original.ADDRESS = Model_SysUser.ADDRESS;
                Model_SysUser_Original.USER_PYM = Model_SysUser.USER_PYM;
            }
        }
        else
        {
            Model_SysUser = new CommonLib.Model.SYS_USER();
            Model_SysUser.USER_ID = exttxtf_user_id.Text;
        }
        
        Model_SysUser.USER_NAME = exttxtf_USER_NAME.Text;
        string sEncode = CommonLib.ComMon.StringCommon.StringEncode(exttxtf_USER_PASSWORD.Text);
        Model_SysUser.USER_PASSWORD = sEncode;
        Model_SysUser.DEPT_ID = extHid_coboDeptId.Text.Trim();
        if (rdoIS_MANAGER1.Checked)
            Model_SysUser.IS_MANAGER = 1;
        else
            Model_SysUser.IS_MANAGER = 0;
        if (exttxtf_DISPLAY_ORDER.Text != "")
            Model_SysUser.DISPLAY_ORDER = int.Parse(exttxtf_DISPLAY_ORDER.Text);
        Model_SysUser.CONTACT_PHONE = exttxtf_CONTACT_PHONE.Text;
        Model_SysUser.INNER_PHONE = exttxtf_INNER_PHONE.Text;
        Model_SysUser.OFFICE_PHONE = exttxtf_OFFICE_PHONE.Text;
        Model_SysUser.HOME_PHONE = exttxtf_HOME_PHONE.Text;
        Model_SysUser.E_MAIL = exttxtf_E_MAIL.Text;
        Model_SysUser.ADDRESS = exttxtf_ADDRESS.Text;
        Model_SysUser.OTHER_USER1 = exttrig_OTHER_USER1.Text;
        Model_SysUser.OTHER_PWD1 = exttxtf_OTHER_PWD1.Text;
        Model_SysUser.REMARK = exttare_REMARK.Text;
        Model_SysUser.user_duty = exttxtf_USER_DUTY.Text;
        Model_SysUser.USER_PYM = exttxtf_USER_PYM.Text.Trim();

        DataTable RoleFunnTable = Session["tmptable"] as DataTable;
        CommonLib.Model.SYS_OPERATOR_ROLE[] fun_models = null;
        if (RoleFunnTable != null)
        {
            fun_models = new CommonLib.Model.SYS_OPERATOR_ROLE[RoleFunnTable.Rows.Count];
            for (int i = 0; i < RoleFunnTable.Rows.Count; i++)
            {
                CommonLib.Model.SYS_OPERATOR_ROLE fun_model = new CommonLib.Model.SYS_OPERATOR_ROLE();
                fun_model.USER_ID = Model_SysUser.USER_ID;
                fun_model.MASTER_ID = int.Parse(RoleFunnTable.Rows[i]["MASTER_ID"].ToString());
                fun_models[i] = fun_model;
            }
        }
        //保存
        if (ViewState["ObjId"].ToString() == "Add")
        {
            if (CommonLib.BLL.SYS_USER.AddTrans(Model_SysUser, fun_models) > 0)
                ViewState["ObjId"] = Model_SysUser.USER_ID;
            else
                tmp = false;
        }
        else
        {
            if (Model_SysUser_Original != null)
            {
                Model_SysUser = Model_SysUser_Original;
            }

            if (CommonLib.BLL.SYS_USER.UpdateTrans(Model_SysUser, fun_models) <= 0)
                tmp = false;
        }
        return tmp;
    }
    #endregion
}
